package com.hb.umsp.service;

import com.hb.umsp.entity.HbUser;
import com.hb.umsp.entity.HbUserToMenuGrp;
import com.hb.umsp.mapper.HbUserToAttendanceMapper;
import com.hb.umsp.mapper.HbUserToMenuGrpMapper;
import com.hb.umsp.util.ad.Adlogin;
import com.hb.umsp.util.token.TokenUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Map;

@Service
public class LoginUser {

    Logger logger = LoggerFactory.getLogger(LoginUser.class);

    @Autowired
    TokenUtil tokenUtil;

    @Autowired
    Adlogin adlogin;

    @Autowired
    UserService userService;

    @Autowired
    HbUserToMenuGrpMapper hbUserToMenuGrpMapper;

    @Autowired
    HbUserToAttendanceMapper hbUserToAttendanceMapper;

    @Transactional
    public String login(String username,String password){

        Map<String,String> map = adlogin.Adlogin(username,password);
        if (map.size() <= 0) {
            logger.info("域名验证失败，请验证域账号！");
            return "fail";
        }

        //第一次登陆给默认最小权限及菜单
        HbUser user = userService.findHhUser(username);
        if (user == null) {
            logger.info("登陆用户名：" + username);
            // 如果系统中没有用户信息，默认插入用户信息
            user = new HbUser();
            user.setUsername(username);
            user.setUserrole("user");
            user.setName(map.get("displayName"));  //用户姓名
            user.setAttendanceCode(map.get("description"));  //考勤编码（员工工号）
            user.setEmail(map.get("userPrincipalName"));
//            //查询考勤编码
//            HbUserToAttendance hbUserToAttendance = hbUserToAttendanceMapper.selectByUsername(username);
//            if (hbUserToAttendance != null) {
//                user.setAttendanceCode(hbUserToAttendance.getAttendanceCode());
//            }
            userService.insertUser(user);
            logger.info("用户考勤编码：" + user.getAttendanceCode());
            // 插入角色信息
            HbUserToMenuGrp hbUserToMenuGrp = new HbUserToMenuGrp();
            hbUserToMenuGrp.setUsername(username);
            hbUserToMenuGrp.setMenugrpcode("02"); // 默认普通用户角色
            hbUserToMenuGrpMapper.insertSelective(hbUserToMenuGrp);
            logger.info("插入用户及角色信息成功：" + username);
        }

        return tokenUtil.getToken(username,user.getUserrole(),user.getAttendanceCode());
    }

}
